#include "asynctask.h"

AsyncTask::AsyncTask(ExecutionObjectInterface *executionObject, QObject *parent) :
    QObject(parent)
{
    if (executionObject != NULL) {
        executionObject_ = executionObject;
        thread_ = new QThread(this);

        executionObject->moveToThread(thread_);

        connect(executionObject_, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
        connect(thread_, SIGNAL(started()), executionObject_, SLOT(doInBackground()));
        connect(executionObject_, SIGNAL(processFinished()), thread_, SLOT(quit()));
        connect(executionObject_, SIGNAL(processFinished()), executionObject_, SLOT(onPostExecute()));
        connect(executionObject_, SIGNAL(objectFinished()), executionObject_, SLOT(deleteLater()));
        connect(thread_, SIGNAL(finished()), executionObject_, SLOT(deleteLater()));
        connect(this, SIGNAL(destroyed()), thread_, SLOT(deleteLater()));
        connect(this, SIGNAL(destroyed()), executionObject_, SLOT(deleteLater()));
    }
    else {
        executionObject_ = NULL;
        thread_ = NULL;
        emit error(tr("Execution Object is NULL"));
    }
}

void AsyncTask::execute()
{
    if (executionObject_ != NULL && thread_ != NULL) {
        thread_->start();
    }
    else {
        emit error(tr("Attempt to execute with NULL parameters"));
    }
}

void AsyncTask::errorString(QString errorStr)
{
    emit error(errorStr);
}

AsyncTask::~AsyncTask()
{
    if (thread_ != NULL) {
        if (thread_->isRunning()) {
            thread_->exit();
        }

        delete thread_;
        thread_ = NULL;
    }
}



